import streamlit as st
import random
import time
import pandas as pd
import os

# 初始化游戏状态
if 'initialized' not in st.session_state:
    st.session_state.initialized = True
    st.experimental_rerun()

# 初始化游戏状态
if 'game_started' not in st.session_state:
    st.session_state.game_started = False
if 'difficulty' not in st.session_state:
    st.session_state.difficulty = '简单'
if 'words_matrix' not in st.session_state:
    st.session_state.words_matrix = []
if 'matched_pairs' not in st.session_state:
    st.session_state.matched_pairs = 0
if 'total_pairs' not in st.session_state:
    st.session_state.total_pairs = 0
if 'start_time' not in st.session_state:
    st.session_state.start_time = 0
if 'elapsed_time' not in st.session_state:
    st.session_state.elapsed_time = 0
if 'eliminated_words' not in st.session_state:
    st.session_state.eliminated_words = []
if 'word_dict' not in st.session_state:
    st.session_state.word_dict = {}
if 'final_score' not in st.session_state:
    st.session_state.final_score = 0

# 居中显示GIF的CSS样式
centered_gif_style = """
<style>
    .centered-gif-container {
        display: flex;
        justify-content: center;
        margin: 20px 0;
    }
    .centered-gif-container img {
        max-width: 300px;
        height: auto;
    }
</style>
"""

# 从Photo目录随机选择一个GIF文件
def get_random_gif():
    gif_dir = "/home/yokay/mythidea"
    
    # 确保目录存在
    if not os.path.exists(gif_dir):
        st.error(f"找不到Photo目录，请在程序同级目录创建Photo文件夹并放入GIF文件")
        return None
    
    # 获取所有GIF文件
    gif_files = [f for f in os.listdir(gif_dir) if f.lower().endswith(('.gif', '.GIF'))]
    
    if not gif_files:
        st.error(f"Photo目录中没有找到GIF文件，请添加至少一个GIF文件")
        return None
    
    # 随机选择一个GIF文件
    return os.path.join(gif_dir, random.choice(gif_files))

# 读取CSV文件中的单词
def load_words_from_csv():
    try:
        # 检查文件是否存在
        if not os.path.exists('/home/yokay/mythidea/word.csv'):
            st.error("找不到word.csv文件，请确保文件在正确的路径下")
            return {}
        
        # 读取CSV文件
        df = pd.read_csv('/home/yokay/mythidea/word.csv')
        
        # 确保CSV文件有必要的列
        if len(df.columns) < 2:
            st.error("CSV文件格式不正确，需要至少两列（英文和中文）")
            return {}
        
        # 创建英文到中文的映射字典
        word_dict = {}
        for _, row in df.iterrows():
            english = str(row.iloc[0]).strip()
            chinese = str(row.iloc[1]).strip()
            if english and chinese:  # 确保单词和解释都不为空
                word_dict[english] = chinese
        
        return word_dict
    except Exception as e:
        st.error(f"读取CSV文件时出错: {str(e)}")
        return {}

# 根据难度生成单词卡片
def generate_words(difficulty, word_dict):
    if difficulty == '简单':
        size = 4
        pairs = 8  # 4x4网格，8对单词（16个卡片）
    elif difficulty == '中等':
        size = 6
        pairs = 18  # 6x6网格，18对单词（36个卡片）
    else:  # 困难
        size = 8
        pairs = 32  # 8x8网格，32对单词（64个卡片）
    
    # 确保有足够的单词
    if len(word_dict) < pairs:
        st.error(f"单词数量不足，需要{pairs}个不同的单词，但只有{len(word_dict)}个")
        return [], 0, 0
    
    # 随机选择单词
    selected_words = random.sample(list(word_dict.keys()), pairs)
    
    # 创建单词对（每个单词出现两次）
    words_for_matrix = []
    for word in selected_words:
        words_for_matrix.append({
            'english': word,
            'chinese': word_dict[word]
        })
        words_for_matrix.append({
            'english': word,
            'chinese': word_dict[word]
        })
    
    # 随机打乱单词顺序
    random.shuffle(words_for_matrix)
    
    # 创建网格矩阵
    matrix = []
    index = 0
    
    for i in range(size):
        row = []
        for j in range(size):
            if index < len(words_for_matrix):
                word_data = words_for_matrix[index]
                index += 1
                row.append({
                    'english': word_data['english'],
                    'chinese': word_data['chinese'],
                    'matched': False,
                    'position': (i, j)
                })
            else:
                # 填充空卡片
                row.append({
                    'english': '',
                    'chinese': '',
                    'matched': True,
                    'position': (i, j)
                })
        matrix.append(row)
    
    return matrix, size, pairs

# 处理卡片移动逻辑
def move_cards(matrix):
    size = len(matrix)
    
    # 按列处理卡片移动
    for j in range(size):
        # 收集非匹配的单词
        non_matched_words = []
        for i in range(size):
            if not matrix[i][j]['matched'] and matrix[i][j]['english']:
                non_matched_words.append(matrix[i][j])
        
        # 填充新的列
        for i in range(size):
            if i < len(non_matched_words):
                matrix[i][j] = non_matched_words[i]
                matrix[i][j]['matched'] = False
            else:
                matrix[i][j] = {
                    'english': '',
                    'chinese': '',
                    'matched': True,
                    'position': (i, j)
                }
    
    return matrix

# 显示游戏统计信息
def show_stats():
    st.write("### 游戏统计")
    
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.write(f"已匹配: {st.session_state.matched_pairs}/{st.session_state.total_pairs}")
    
    with col2:
        st.write(f"得分: {st.session_state.matched_pairs * 10}")
    
    with col3:
        if st.session_state.game_started:
            st.write(f"用时: {st.session_state.elapsed_time:.1f}秒")
        else:
            st.write("用时: 0秒")
    
    # 显示已消除的单词
    st.write("### 已消除的单词")
    if st.session_state.eliminated_words:
        # 创建包含英文和中文的DataFrame
        words_data = []
        
        # 确保每个元素都是字典
        for item in st.session_state.eliminated_words:
            if isinstance(item, dict):
                words_data.append({
                    "英文": item.get('english', ''),
                    "中文": item.get('chinese', '')
                })
            else:
                # 如果不是字典，尝试从word_dict获取信息
                english = str(item)
                chinese = st.session_state.word_dict.get(english, "")
                words_data.append({
                    "英文": english,
                    "中文": chinese
                })
        
        df = pd.DataFrame(words_data)
        st.table(df)
    else:
        st.write("还没有消除任何单词")

# 根据时间计算最终得分
def calculate_final_score():
    # 基础分数：每对10分
    base_score = st.session_state.matched_pairs * 10
    
    # 时间奖励：根据完成时间给予额外分数
    time_bonus = 0
    elapsed_time = st.session_state.elapsed_time
    
    # 根据难度设置不同的时间奖励标准
    if st.session_state.difficulty == '简单':
        if elapsed_time < 30:  # 30秒内完成
            time_bonus = 50
        elif elapsed_time < 60:  # 1分钟内完成
            time_bonus = 30
        elif elapsed_time < 120:  # 2分钟内完成
            time_bonus = 10
    elif st.session_state.difficulty == '中等':
        if elapsed_time < 60:  # 1分钟内完成
            time_bonus = 80
        elif elapsed_time < 120:  # 2分钟内完成
            time_bonus = 50
        elif elapsed_time < 240:  # 4分钟内完成
            time_bonus = 20
    else:  # 困难
        if elapsed_time < 120:  # 2分钟内完成
            time_bonus = 120
        elif elapsed_time < 240:  # 4分钟内完成
            time_bonus = 80
        elif elapsed_time < 480:  # 8分钟内完成
            time_bonus = 40
    
    # 计算最终得分
    final_score = base_score + time_bonus
    return final_score, time_bonus

# 显示游戏结束动画
def show_game_over_animation():

    # 显示居中的GIF
    st.markdown(centered_gif_style, unsafe_allow_html=True)
    gif_path = get_random_gif()

    if gif_path:
        st.markdown(centered_gif_style, unsafe_allow_html=True)
        st.image(gif_path, use_column_width=True, output_format="GIF")

    # 添加庆祝动画
    st.balloons()
    st.snow()
    

# 开始新游戏
def start_new_game():
    # 加载单词
    st.session_state.word_dict = load_words_from_csv()
    
    # 确保有单词可用
    if not st.session_state.word_dict:
        st.error("无法加载单词，请检查CSV文件")
        return
    
    st.session_state.game_started = True
    st.session_state.words_matrix, size, pairs = generate_words(
        st.session_state.difficulty, 
        st.session_state.word_dict
    )
    st.session_state.total_pairs = pairs
    st.session_state.matched_pairs = 0
    st.session_state.start_time = time.time()
    st.session_state.elapsed_time = 0
    st.session_state.eliminated_words = []
    st.session_state.selected_cards = []
    st.session_state.final_score = 0

# 游戏主界面和逻辑
st.title("单词消消乐")

# 游戏控制 - 只有难度选择
col1 = st.columns(1)
with col1[0]:
    st.session_state.difficulty = st.selectbox(
        "选择难度",
        ["简单", "中等", "困难"]
    )

# 使用CSS样式使按钮占据整行宽度
button_style = """
<style>
    div.stButton > button {
        width: 100%;
        font-size: 18px;
        padding: 10px;
    }
</style>
"""
st.markdown(button_style, unsafe_allow_html=True)

# 开始游戏按钮单独一行，占据整行宽度
if st.button("开始游戏"):
    start_new_game()

# 显示游戏统计
if st.session_state.game_started:
    st.session_state.elapsed_time = time.time() - st.session_state.start_time
    show_stats()
    
    st.write("### 游戏区域")
    
    # 为所有卡片设置统一的样式
    card_button_style = """
    <style>
        div.stButton > button {
            width: 100%;
            height: 80px;
            font-size: 16px;
            white-space: normal;
            word-wrap: break-word;
        }
    </style>
    """
    st.markdown(card_button_style, unsafe_allow_html=True)
    
    # 显示单词卡片
    size = len(st.session_state.words_matrix)
    for i in range(size):
        cols = st.columns(size)
        for j in range(size):
            card = st.session_state.words_matrix[i][j]
            
            with cols[j]:
                if card['matched']:
                    # 匹配成功的卡片显示为空白
                    st.empty()
                else:
                    # 显示单词卡片
                    if card['english']:  # 确保单词不为空
                        if st.button(f"{card['english']}", key=f"card_{i}_{j}"):
                            # 记录选中的卡片
                            if 'selected_cards' not in st.session_state:
                                st.session_state.selected_cards = []
                            
                            st.session_state.selected_cards.append({
                                'i': i,
                                'j': j,
                                'english': card['english'],
                                'chinese': card['chinese']
                            })
                            
                            # 如果选中了两个单词，检查是否匹配
                            # 如果选中了两个单词，检查是否匹配
                            if len(st.session_state.selected_cards) == 2:
                                card1 = st.session_state.selected_cards[0]
                                card2 = st.session_state.selected_cards[1]
                                
                                # 确保是两张不同位置的卡片
                                if (card1['i'], card1['j']) == (card2['i'], card2['j']):
                                    # 同一张卡片，不执行匹配逻辑
                                    st.session_state.selected_cards = []  # 清空选中状态
                                    st.experimental_rerun()  # 刷新页面
                                    continue  # 跳过后续匹配逻辑
                                
                                if card1['english'] == card2['english']:
                                    # 匹配成功
                                    st.session_state.words_matrix[card1['i']][card1['j']]['matched'] = True
                                    st.session_state.words_matrix[card2['i']][card2['j']]['matched'] = True
                                    st.session_state.matched_pairs += 1
                                    
                                    # 添加到已消除单词列表
                                    word_info = {
                                        'english': card1['english'],
                                        'chinese': card1['chinese']
                                    }
                                    
                                    # 检查单词是否已存在于列表中
                                    word_exists = False
                                    for item in st.session_state.eliminated_words:
                                        if isinstance(item, dict) and item.get('english') == word_info['english']:
                                            word_exists = True
                                            break
                                    
                                    if not word_exists:
                                        st.session_state.eliminated_words.append(word_info)
                                    
                                    # 移动卡片填补空白
                                    st.session_state.words_matrix = move_cards(st.session_state.words_matrix)
                                    
                                    # 检查游戏是否结束
                                    if st.session_state.matched_pairs == st.session_state.total_pairs:
                                        show_game_over_animation()
                                        time.sleep(3)
                                else:
                                    # 匹配失败，翻转回去
                                    time.sleep(0.5)
                                
                                # 重置选中的单词
                                st.session_state.selected_cards = []
                                st.experimental_rerun()

